<?php
/**
 * Copyright 2009 Joe Dotoff
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Compiler class
 *
 * @package     PDog
 * @subpackage  Runtime
 * @author      Joe D. <nonultimate@gmail.com>
 * @license     Apache License Version 2.0
 * @version     $Id: Compiler.php 33 2009-04-21 01:03:44Z nonultimate $
 */
class Compiler
{
    /**
     * Compile a single script file to bytecode
     *
     * @param  string  $file  The file to compile
     * @param  string  $out   The output path for bytecode file
     * @return void
     */
    public static function compile($file, $out = null)
    {
        if (!is_file($file)) {
            return false;
        }
        if (!extension_loaded('bcompiler')) {
            $is_loaded = false;
            try {
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    $is_loaded = dl('php_bcompiler.dll');
                } else {
                    $is_loaded = dl('bcompiler.so');
                }
            } catch (Exception $e) {
                $is_loaded = false;
            }
            if (false === $is_loaded) {
                die('Bcompiler extension not loaded');
            }
        }
        if (null === $out) {
            $out = preg_replace('/\.php$/i', '.phc', $file);
        }
        if (__FILE__ !== $file) {
            $fp = fopen($out, 'w');
            bcompiler_write_header($fp);
            bcompiler_write_file($fp, $file);
            bcompiler_write_footer($fp);
            fclose($fp);
        }
    }
    /**
     * Compile all script files in a directory
     *
     * @param  string  $path  The script directory to compile
     * @return void
     */
    public static function compileAll($path)
    {
        if (!is_dir($path)) {
             return false;
        }
        $path = realpath($path);
        $dir = dir($path);
        while (false !== ($entry = $dir->read())) {
            if ($entry != '.' and $entry != '..') {
                $file = $path . DIRECTORY_SEPARATOR . $entry;
                if (is_file($file)) {
                    if (preg_match('/\.php$/i', $file)) {
                        Compiler::compile($file);
                    }
                } else {
                    if (!preg_match('/^\./', $entry)) {
                        Compiler::compileAll($file);
                    }
                }
            }
        }
        $dir->close();
    }
}
?>